﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using CarlosAg.ExcelXmlWriter;
using Edge.Common;
using Edge.Common.Services;
using Edge.Common.Utils;
using Shop.Business.Domain.Catalog;
using Shop.Business.Domain.Catalog.Parameter;
using Shop.Business.Domain.Customers;
using Shop.Business.Domain.Pricing;
using Parameter=Shop.Business.Domain.Catalog.Parameter.Parameter;

namespace Shop.Business.Upload
{
    public class UploadCatalog
    {

        private HttpPostedFile file;
        private Customer currentCustomer;
        private bool updateQty = false;
        private Workbook workbook;

        public HttpPostedFile File
        {
            get { return file; }
            set { file = value; }
        }

        public bool UpdateQty
        {
            get { return updateQty; }
            set { updateQty = value; }
        }

        public Customer CurrentCustomer
        {
            get { return currentCustomer; }
            set { currentCustomer = value; }
        }

        public UploadCatalog()
        {
        }

        public UploadCatalog(HttpPostedFile file, bool updateQty, Customer currentCustomer)
        {
            this.file = file;
            this.updateQty = updateQty;
            this.currentCustomer = currentCustomer;
            LoadWorkbook();
        }



        private ProductGroup GetGroup(string groupName, Brand brand, Category category)
        {
            return GetGroup(groupName, brand, category, string.Empty);
        }

        private ProductGroup GetGroup(string groupName, Brand brand, Category category, string brandArt)
        {
            
            ProductGroup productGroup = null;
            if (!StringUtils.IsEmptyOrNull(groupName))
            {
                ProductGroupFilter groupFilter = new ProductGroupFilter();
                if (StringUtils.IsEmptyOrNull(brandArt))
                    groupFilter.Keyword = groupName;
                else
                    groupFilter.BrandArt = brandArt;
                groupFilter.Brand = brand;
                groupFilter.ShowInVis = true;
                if (Locator.GetService<IProductGroupManager>().Count(groupFilter) == 0)
                {
                    if (!StringUtils.IsEmptyOrNull(brandArt))
                    {
                        groupFilter.BrandArt = "";
                        groupFilter.Keyword = groupName;
                        if (Locator.GetService<IProductGroupManager>().Count(groupFilter) == 0)
                        {
                            productGroup = new ProductGroup();
                            productGroup.Name = groupName;
                            productGroup.Brand = brand;
                            productGroup.Category = category;
                            productGroup.CreatedBy = currentCustomer;
                            Locator.GetService<IProductGroupManager>().Save(productGroup);
                        }
                        else
                        {
                            productGroup = CollectionsUtils.GetElement(
                       Locator.GetService<IProductGroupManager>().Find(FetchOptions.All, groupFilter), 0);
                        }
                    }
                    else
                    {

                        productGroup = new ProductGroup();
                        productGroup.Name = groupName;
                        productGroup.Brand = brand;
                        productGroup.Category = category;
                        productGroup.CreatedBy = currentCustomer;
                        Locator.GetService<IProductGroupManager>().Save(productGroup);
                    }
                }
                else
                {
                    productGroup = CollectionsUtils.GetElement(
                        Locator.GetService<IProductGroupManager>().Find(FetchOptions.All, groupFilter), 0);
                }
            }
            return productGroup;
        }


        private Category GetCategory(string categoryName)
        {
            Category category = null;
            if (!StringUtils.IsEmptyOrNull(categoryName))
            {
                CategoryFilter categoryFilter = new CategoryFilter();
                categoryFilter.Keyword = categoryName;
                if (Locator.GetService<ICategoryManager>().Count(categoryFilter) == 0)
                {
                    category = new Category(categoryName, "", Locator.GetService<ICategoryManager>().Load(1));
                    category.CreatedBy = currentCustomer;
                    Locator.GetService<ICategoryManager>().Save(category);
                }
                else
                {
                    category =
                        CollectionsUtils.GetElement(
                            Locator.GetService<ICategoryManager>().Find(FetchOptions.All, categoryFilter), 0);
                }
            }
            return category;
        }


        private Product GetProduct(string productName, ProductGroup group, string brandArt)
        {
            Product product = null;
            if (!StringUtils.IsBlankOrNull(productName))
            {
                ProductFilter productFilter = new ProductFilter();
                productFilter.Keyword = productName;
                productFilter.Group = group;
                productFilter.BrandArt = brandArt;
                if (Locator.GetService<IProductManager>().Count(productFilter) == 0)
                {
                    product = new Product();
                    product.Name = productName;
                    product.CreatedBy = currentCustomer;
                    product.Group = group;
                    product.BrandArt = brandArt;
                }
                else
                {
                    product = CollectionsUtils.GetElement(
                        Locator.GetService<IProductManager>().Find(FetchOptions.All, productFilter), 0);
                }
                product.Visible = true;
                Locator.GetService<IProductManager>().Save(product);
            }
            return product;

        }

        private Brand GetBrand(string brandName)
        {
            Brand brand = null;
            if (!StringUtils.IsEmptyOrNull(brandName))
            {
                BrandFilter brandFilter = new BrandFilter();
                brandFilter.Keyword = brandName;
                if (Locator.GetService<IBrandManager>().Count(brandFilter) == 0)
                {
                    brand = new Brand(brandName, "");
                    brand.CreatedBy = currentCustomer;
                    Locator.GetService<IBrandManager>().Save(brand);
                }
                else
                {
                    brand =
                        CollectionsUtils.GetElement(
                            Locator.GetService<IBrandManager>().Find(FetchOptions.All, brandFilter), 0);
                }
            }
            return brand;
        }

        private Parameter GetParameter(string parameterName)
        {
            Parameter parameter = null;
            ParameterFilter parameterFilter = new ParameterFilter();
            parameterFilter.Keyword = parameterName;
            if (Locator.GetService<IParameterManager>().Count(parameterFilter) == 0)
            {
                parameter = new Parameter();
                parameter.Name = parameterFilter.Keyword;
                Locator.GetService<IParameterManager>().Save(parameter);
            }
            else
            {
                parameter = CollectionsUtils.GetElement(
                        Locator.GetService<IParameterManager>().Find(FetchOptions.All, parameterFilter), 0);
            }
            return parameter;
        }

        public ParameterValue GetParameterValue(string valueName, Parameter parameter)
        {
            ParameterValueFilter parameterValueFilter = new ParameterValueFilter();
            parameterValueFilter.Keyword = valueName;
            parameterValueFilter.Parameter = parameter;
            ParameterValue parameterValue = null;
            if (Locator.GetService<IParameterValueManager>().Count(parameterValueFilter) == 0)
            {
                parameterValue = new ParameterValue();
                parameterValue.Value = parameterValueFilter.Keyword;
                parameterValue.Parameter = parameter;
                Locator.GetService<IParameterValueManager>().Save(parameterValue);
            }
            else
            {
                parameterValue = CollectionsUtils.GetElement(
                        Locator.GetService<IParameterValueManager>().Find(FetchOptions.All, parameterValueFilter), 0);
            }
            return parameterValue;
        }

        private PriceItem GetPriceItem(Product product, decimal wholesllPrice, decimal price, int qty, string guid)
        {
            PriceItem priceItem = null;
            PriceItemFilter priceItemFilter = new PriceItemFilter();
            priceItemFilter.Product = product;
            priceItemFilter.WholesellPrice = wholesllPrice;
            priceItemFilter.Price = price;
            if (Locator.GetService<IPriceItemManager>().Count(priceItemFilter) == 0)
            {
                priceItem = new PriceItem();
                priceItem.Product = product;
                priceItem.CreatedBy = currentCustomer;
                priceItem.Price = price;
                priceItem.WholesellPrice = wholesllPrice;
                priceItem.Qty = qty;
            }
            else 
            {
                priceItem = CollectionsUtils.GetElement(
                        Locator.GetService<IPriceItemManager>().Find(FetchOptions.All, priceItemFilter), 0);
                if (UpdateQty)
                {
                    priceItem.Qty += qty;
                    priceItem.CreateDate = DateTime.Now;
                }

            }
            priceItem.Note = guid;
            Locator.GetService<IPriceItemManager>().Save(priceItem);
            return priceItem;
        }

        private void LoadWorkbook()
        {
            workbook = null;
            if (file != null && currentCustomer != null)
            {
                workbook = new Workbook();
                workbook.Load(file.InputStream);
            }
        }

        public int Upload()
        {
            int ret = 0;
            if (workbook != null)
            {
                //string guid = Guid.NewGuid().ToString();
                Parameter parameterSize = GetParameter("Размер");
                Parameter parameterColor = GetParameter("Цвет");
                int i = 0;
                while (i < workbook.Worksheets[0].Table.Rows.Count && !StringUtils.IsBlankOrNull(workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text))
                {
                    string brandName = workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text;
                    string groupName = workbook.Worksheets[0].Table.Rows[i].Cells[1].Data.Text;
                    if (groupName.Contains(","))
                        groupName = groupName.Substring(0, groupName.IndexOf(','));
                    if (groupName.Contains("("))
                        groupName = groupName.Substring(0, groupName.IndexOf('('));
                    string[] groupAttr = groupName.Split(' ');
                    string brandArt = groupAttr[0];
                    string categoryName = "Разобрать!";
                    if (groupAttr.Length > 1)
                        categoryName = groupAttr[1];
                    groupName = groupName.Remove(0, brandArt.Count() + 1);
                    groupName += workbook.Worksheets[0].Table.Rows[i].Cells[2].Data.Text;
                    string[] sizeArray = workbook.Worksheets[0].Table.Rows[i].Cells[3].Data.Text.Split(',');
                    decimal wholesllPrice = 0;
                    decimal price = 0;
                    int qty = 0;
                    try
                    {
                        qty = Convert.ToInt32(workbook.Worksheets[0].Table.Rows[i].Cells[4].Data.Text);
                        wholesllPrice =
                            Convert.ToDecimal(workbook.Worksheets[0].Table.Rows[i].Cells[5].Data.Text.Replace('.', ','));
                        price = GeneratePrice(wholesllPrice);
                    }
                    catch
                    {

                    }
                    Brand brand = GetBrand(brandName);
                    Category category = GetCategory(categoryName);
                    ProductGroup group = GetGroup(groupName, brand, category,brandArt);
                    
                    for (int j = 0; j < sizeArray.Count(); j++)
                    {
                        string productName = groupName + ", размер " + sizeArray[j];
                        ParameterValue parameterSizeValue = GetParameterValue(sizeArray[j], parameterSize);
                        Product product = GetProduct(productName, group, brandArt);
                        Locator.GetService<IParameterValueManager>().SetProductPatameterValues(product,
                                                                                               parameterSizeValue.Id);
                        PriceItem priceItem = GetPriceItem(product, wholesllPrice, price, qty, "");
                    }
                    i++;
                }
                //Locator.GetService<IPriceItemManager>().SetProductInvisible(guid);
            }
            return ret;
        }

        public int Upload(string brandName, int discount)
        {
            int ret = 0;
            if (workbook != null)
            {
                int i = 1;
                Brand brand = GetBrand(brandName);
                Parameter parameterSize = GetParameter("Размер");
                string categoryName = "Разобрать!";
                string collectionName = "Morlin";
                while (i < workbook.Worksheets[0].Table.Rows.Count && !StringUtils.IsBlankOrNull(workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text))
                {
                    if (workbook.Worksheets[0].Table.Rows[i].Cells.Count > 1 && (!StringUtils.IsBlankOrNull(workbook.Worksheets[0].Table.Rows[i].Cells[1].Data.Text)))
                    {
                        string groupName = workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text;
                        if (groupName.Contains(","))
                            groupName = groupName.Substring(0, groupName.LastIndexOf(','));
                        if (groupName.Contains("("))
                            groupName = groupName.Substring(0, groupName.LastIndexOf('('));
                        string[] groupAttr = groupName.Split(' ');
                        string brandArt = groupAttr[0];
                        if (groupAttr.Length > 1)
                            categoryName = groupAttr[1];
                        if (groupName.Contains(brandArt))
                            groupName = groupName.Remove(0, brandArt.Count() + 1);
                        groupName += collectionName;
                        string[] sizeArray = workbook.Worksheets[0].Table.Rows[i].Cells[1].Data.Text.Split(',');
                        decimal wholesllPrice = 0;
                        decimal price = 0;
                        int qty = 0;
                        try
                        {
                            wholesllPrice =
                                Convert.ToDecimal(workbook.Worksheets[0].Table.Rows[i].Cells[2].Data.Text.Replace('.',
                                                                                                                  ','));
                            wholesllPrice = wholesllPrice - wholesllPrice*discount/100;
                            price = GeneratePrice(wholesllPrice);
                        }
                        catch
                        {

                        }
                        Category category = GetCategory(categoryName);
                        ProductGroup group = GetGroup(groupName, brand, category,brandArt);

                        for (int j = 0; j < sizeArray.Count(); j++)
                        {
                            string productName = groupName + ", размер " + sizeArray[j];
                            ParameterValue parameterSizeValue = GetParameterValue(sizeArray[j], parameterSize);
                            Product product = GetProduct(productName, group, brandArt);
                            Locator.GetService<IParameterValueManager>().SetProductPatameterValues(product,
                                                                                                   parameterSizeValue.Id);
                            PriceItem priceItem = GetPriceItem(product, wholesllPrice, price, qty, "");
                        }
                    }
                    else
                    {
                        collectionName = workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text;
                    }
                    i++;
                    
                }
            }
            return ret;
        }

        private int GeneratePrice(decimal wslPrice)
        {
            decimal price = 0;
            int margin = 40;
            if (wslPrice < 200)
                margin = 50;
            else if (wslPrice < 1000)
                margin = 45;
            price = Math.Round(wslPrice + wslPrice*margin/100);
            if (price < 300 )
                price = Math.Round(price / 5) * 5;
            else
                price = Math.Round(price/10)*10;
            return (int)price;
        }

        public int UploadAmameru(Brand brand)
        {
            int ret = 0;
            if (workbook != null)
            {
                int i = 1;
                Parameter parameterSize = GetParameter("Размер");
                Category category = GetCategory(brand.Name);
                string[] sizeArray = { "S", "L" };
                while (i < workbook.Worksheets[0].Table.Rows.Count && !StringUtils.IsBlankOrNull(workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text))
                {
                    if (!StringUtils.IsBlankOrNull(workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text) && (workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text != "ВСЕГО"))
                    {
                        string groupName = "Рюкзак-слинг " + workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text;
                        string brandArt = workbook.Worksheets[0].Table.Rows[i].Cells[0].Data.Text;
                        string description = string.Empty;
                        if (workbook.Worksheets[0].Table.Rows[i].Cells.Count > 5)
                            description = workbook.Worksheets[0].Table.Rows[i].Cells[5].Data.Text;
                        decimal wholesllPrice = 0;
                        decimal price = 0;
                        try
                        {
                            price =
                                Convert.ToDecimal(workbook.Worksheets[0].Table.Rows[i].Cells[4].Data.Text.Replace('.',
                                                                                                                  ','));
                            wholesllPrice = price - price * 10 / 100;
                        }
                        catch
                        {

                        }
                        if (price > 0)
                        {
                            ProductGroup group = GetGroup(groupName, brand, category,brandArt);
//                            group.Description = description;
//                            Locator.GetService<IProductGroupManager>().Save(group);
                            for (int j = 0; j < sizeArray.Count(); j++)
                            {
                                string productName = "Размер " + sizeArray[j];
                                int qty = 0;
                                try
                                {
                                    qty =
                                        Convert.ToInt32(workbook.Worksheets[0].Table.Rows[i].Cells[j + 1].Data.Text);
                                }
                                catch
                                {

                                }
                                ParameterValue parameterSizeValue = GetParameterValue(sizeArray[j], parameterSize);
                                Product product = GetProduct(productName, group, brandArt);
                                Locator.GetService<IParameterValueManager>().SetProductPatameterValues(product,
                                                                                                       parameterSizeValue
                                                                                                           .Id);
                                PriceItem priceItem = GetPriceItem(product, wholesllPrice, price, qty, "");
                            }
                        }
                    }
                   
                    i++;

                }
            }
            return ret;
        }
    }
}

